package com.rh.number.config;

import com.rh.number.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.naming.AuthenticationException;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    public JwtInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthenticationException {
        // 放行登录接口
        if ("/auth/login".equals(request.getRequestURI())) return true;

        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token) || !token.startsWith("Bearer ")) {
            throw new AuthenticationException("缺失有效 Token");
        }

        try {
            Claims claims = jwtUtil.parseToken(token.replace("Bearer ", ""));
            request.setAttribute("userId", claims.getSubject());
            request.setAttribute("role", claims.get("role"));
            return true;
        } catch (ExpiredJwtException e) {
            throw new AuthenticationException("Token 已过期");
        } catch (JwtException e) {
            throw new AuthenticationException("非法 Token");
        }
    }
}
